Home:ALL Converter>Headers not sent angular-5

Headers not sent angular-5

Ask Time:2018-05-17T14:42:08         Author:Kumail Hussain

Json Formatter

Want to send authorization token in my headers, have tried two different approaches but none of them is sending token i am using against a post request:

Approach 1 is using interceptor:

   @Injectable()
export class AuthInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    console.log('inter')
    const authHeader = 'JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbasdImahQHNdwc25ldC5jb20iLCJ1c2VySWQiOjk5MjI2MDYsImlhdCI6MTUyNjQ2Mzc2NywiZXhwIjoxNTI2NjM2NTY3fQ.v9RjU25kt-neRFHl8P3q5k4VokpJdNm1Kgn7BU10Zoc';
    // Clone the request to add the new header.
    const authReq = req.clone({headers: req.headers.set('Authorization', authHeader)});
    // Pass on the cloned request instead of the original request.
     console.log('intercepted') //got this message in console
    return next.handle(authReq);
  }
}

post function

   post(url: String, data: any) {

    return this.http.post(url, data)
      .map(res => res)
      .catch(this.handleError);
  }

have added in app.module.ts by printing console on service i can see the message on my console

yes intercepted but got this image in result:

no headers present

Second approach is quite simpler and have used it in angular2 but getting error with angular5

      post(url: String, data: any) {
    const headers = new Headers({'Content-Type': 'application/json'});
    headers.append('Authorization',  'JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyasdasdasImhhbXphQHNwc25ldC5jb20iLCJ1c2VySWQiOjk5MjI2MDYsImlhdCI6MTUyNjQ2Mzc2NywiZXhwIjoxNTI2NjM2NTY3fQ.v9RjU25kt-neRFHl8P3q5k4VokpJdNm1Kgn7BU10Zoc');
    const options = new RequestOptions({headers});
    return this.http.post(url, data)
      .map(res => res)
      .catch(this.handleError);
  }

getting this error

response

same things work with angular2 request Options but not with angular5

Token is properly validated and i am sending request through POSTMAN

Author:Kumail Hussain,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/50384940/headers-not-sent-angular-5
David :

It's due to how CORS work. Browsers generally do not sent custom headers such as Authorization header in OPTIONS requests. You need to fix your server so that it does not expect an Authorization header for the OPTIONS request ",
2018-05-17T07:53:22
yy